package com.agent.generator.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import java.net.URI;

/**
 * Cloudflare R2存储配置
 * @author Jeff_Wan
 * @description 配置Cloudflare R2存储的访问凭证和连接参数
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "cloudflare.r2")
public class CloudflareR2Config {

    private String accessKey;

    private String secretKey;

    private String endpoint;

    private String bucketName;

    /**
     * 创建S3客户端实例
     * @return 配置好的S3Client对象
     */
    @Bean
    public S3Client s3Client() {
        return S3Client.builder()
                .endpointOverride(URI.create(endpoint))
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(accessKey, secretKey)
                ))
                .region(Region.of("auto"))
                // 显式指定使用URL Connection客户端
                .httpClient(UrlConnectionHttpClient.create())
                .serviceConfiguration(S3Configuration.builder()
                        // R2必须启用路径样式访问
                        .pathStyleAccessEnabled(true)
                        .build())
                .build();
    }

    /**
     * 获取存储桶名称
     * @return 配置的存储桶名称
     */
    @Bean
    public String bucketName() {
        return bucketName;
    }
}